/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-08-24 18:24:53
 * @LastEditors: cuidm
 * @LastEditTime: 2022-09-28 14:48:30
 */
import { useState, useEffect } from 'react';
import cmdbres from '@/data/cmdbres';
import request from '../../utils/request';
import hcpUtils from '../../utils/hcpUtils';
export async function queryModel() {
    try {
        let res = await request({
            ...cmdbres.queryModelList,
            params: {
                namespace: "default",
            },
        });
        if (res && res.code == 200) {
            return res.data||[]
        } else {
            return [];
        }
    } catch (error) {
        console.log(error);
        return [];
    }
}

function useModelList(moduleCode) {
    const [moduleLoading, setModuleLoading] = useState(true);
    const [moduleData, setModuleData] = useState([]);
    const [module, setModule] = useState();

    useEffect(() => {
        setModuleLoading(true);
        setModuleData([]);
        queryModel()
            .then((res) => {
                setModuleData(res);
                if(moduleCode) {
                    hcpUtils.treeDataIteration(res, function(item) {
                        item.children ??= [];
                        item.definitions ??= [];
                        item.children = [...item.children, ...item.definitions];
                        if(item.moduleCode == moduleCode) {
                            setModule(item);
                            return;
                        }
                    })
                }
                setModuleLoading(false);
            })
            .catch((e) => {
                setModuleData([]);
                setModuleLoading(false);
                throw e;
            });
    }, []);
    return [module, moduleData, moduleLoading];
}

export default useModelList;

